/**
 * 项目导入模态框组件
 */

'use client';

import React, { useState, useCallback } from 'react';
import {
  Modal,
  Button,
  Upload,
  message,
  Steps,
  Table,
  Tag,
  Space,
  Typography,
  Alert,
  Divider,
  Card,
  Progress,
  Result,
} from 'antd';
import {
  UploadOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  FileTextOutlined,
  ProjectOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import { pingCodeAPI } from '../utils/pingcodeApi';

const { Title, Text, Paragraph } = Typography;
const { Step } = Steps;

interface ProjectImportData {
  name: string;
  identifier: string;
  type: string;
  admins: string[];
  description?: string;
  status?: string;
}

interface ImportResult {
  success: boolean;
  project?: any;
  error?: string;
  data: ProjectImportData;
}

interface ProjectImportModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: (results: ImportResult[]) => void;
}

export default function ProjectImportModal({
  visible,
  onCancel,
  onSuccess,
}: ProjectImportModalProps) {
  const [currentStep, setCurrentStep] = useState(0);
  const [fileContent, setFileContent] = useState<string>('');
  const [parsedProjects, setParsedProjects] = useState<ProjectImportData[]>([]);
  const [importing, setImporting] = useState(false);
  const [importResults, setImportResults] = useState<ImportResult[]>([]);
  const [importProgress, setImportProgress] = useState(0);

  // 重置状态
  const resetState = useCallback(() => {
    setCurrentStep(0);
    setFileContent('');
    setParsedProjects([]);
    setImporting(false);
    setImportResults([]);
    setImportProgress(0);
  }, []);

  // 处理文件上传
  const handleFileUpload: UploadProps['customRequest'] = (options) => {
    const { file } = options;
    const reader = new FileReader();
    
    reader.onload = (e) => {
      const content = e.target?.result as string;
      setFileContent(content);
      
      // 解析 Markdown 表格
      const projects = parseMarkdownTable(content);
      if (projects.length > 0) {
        setParsedProjects(projects);
        setCurrentStep(1);
        message.success(`成功解析 ${projects.length} 个项目`);
      } else {
        message.error('未能解析到有效的项目数据，请检查文件格式');
      }
    };
    
    reader.onerror = () => {
      message.error('文件读取失败');
    };
    
    reader.readAsText(file as File);
  };

  // 解析 Markdown 表格
  const parseMarkdownTable = (content: string): ProjectImportData[] => {
    const lines = content.split('\n').filter(line => line.trim());
    const projects: ProjectImportData[] = [];
    
    // 找到表格头部
    let headerIndex = -1;
    for (let i = 0; i < lines.length; i++) {
      if (lines[i].includes('项目名称') && lines[i].includes('项目标识')) {
        headerIndex = i;
        break;
      }
    }
    
    if (headerIndex === -1) {
      console.error('未找到表格头部');
      message.error('文件格式错误：未找到包含"项目名称"和"项目标识"的表格头部');
      return [];
    }
    
    // 解析表格数据（跳过头部和分隔符行）
    for (let i = headerIndex + 2; i < lines.length; i++) {
      const line = lines[i].trim();
      if (!line || !line.startsWith('|')) continue;
      
      const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell);
      
      if (cells.length >= 4) {
        const [name, identifier, type, admins, description = '', status = ''] = cells;
        
        // 验证必填字段
        if (!name || !identifier || !type || !admins) {
          console.warn(`跳过不完整的行: ${line}`);
          continue;
        }
        
        // 解析管理员列表
        const adminList = admins.split(',').map(admin => admin.trim()).filter(admin => admin);
        
        if (adminList.length === 0) {
          console.warn(`项目 ${name} 没有管理员，跳过`);
          continue;
        }
        
        projects.push({
          name,
          identifier,
          type: mapProjectType(type),
          admins: adminList,
          description,
          status,
        });
      }
    }
    
    return projects;
  };

  // 映射项目类型
  const mapProjectType = (type: string): string => {
    const typeMap: Record<string, string> = {
      'scrum': 'scrum',
      'kanban': 'kanban', 
      '看板': 'kanban',
      'waterfall': 'waterfall',
      '瀑布': 'waterfall',
      'hybrid': 'hybrid',
      '混合': 'hybrid',
    };
    
    return typeMap[type.toLowerCase()] || 'scrum';
  };

  // 执行导入
  const handleImport = async () => {
    setImporting(true);
    setCurrentStep(2);
    setImportProgress(0);
    
    try {
      // 调用导入 API
      const response = await fetch('/api/projects/import', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          projects: parsedProjects,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '导入请求失败');
      }

      const data = await response.json();
      
      if (data.success && data.results) {
        setImportResults(data.results);
        setImportProgress(100);
        
        // 显示导入摘要
        const { success: successCount, failed: failedCount } = data.summary;
        console.log(`导入完成: 成功 ${successCount} 个，失败 ${failedCount} 个`);
      } else {
        throw new Error('导入响应格式错误');
      }
      
    } catch (error) {
      console.error('导入失败:', error);
      message.error(`导入失败: ${error instanceof Error ? error.message : '未知错误'}`);
      
      // 创建失败结果
      const failedResults: ImportResult[] = parsedProjects.map(project => ({
        success: false,
        error: error instanceof Error ? error.message : '导入失败',
        data: project,
      }));
      
      setImportResults(failedResults);
    } finally {
      setImporting(false);
      setCurrentStep(3);
    }
  };

  // 完成导入
  const handleComplete = () => {
    onSuccess(importResults);
    resetState();
    onCancel();
  };

  // 取消导入
  const handleCancel = () => {
    resetState();
    onCancel();
  };

  // 表格列定义
  const columns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <Space>
          <ProjectOutlined />
          <Text strong>{text}</Text>
        </Space>
      ),
    },
    {
      title: '项目标识',
      dataIndex: 'identifier',
      key: 'identifier',
      render: (text: string) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: '项目类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap: Record<string, { text: string; color: string }> = {
          scrum: { text: 'Scrum', color: 'blue' },
          kanban: { text: '看板', color: 'green' },
          waterfall: { text: '瀑布', color: 'orange' },
          hybrid: { text: '混合', color: 'purple' },
        };
        const typeInfo = typeMap[type] || { text: type, color: 'default' };
        return <Tag color={typeInfo.color}>{typeInfo.text}</Tag>;
      },
    },
    {
      title: '管理员',
      dataIndex: 'admins',
      key: 'admins',
      render: (admins: string[]) => (
        <Space>
          <TeamOutlined />
          <Text>{Array.isArray(admins) ? admins.join(', ') : (admins || '-')}</Text>
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      render: (text: string) => text || '-',
    },
  ];

  // 结果表格列定义
  const resultColumns = [
    ...columns,
    {
      title: '导入状态',
      key: 'status',
      render: (_: any, record: ImportResult) => {
        if (record.success) {
          const isMockProject = record.project?.id?.startsWith('mock_');
          return (
            <Tag color={isMockProject ? "warning" : "success"} icon={<CheckCircleOutlined />}>
              {isMockProject ? '模拟成功' : '成功'}
            </Tag>
          );
        } else {
          return (
            <Tag color="error" icon={<ExclamationCircleOutlined />}>
              失败
            </Tag>
          );
        }
      },
    },
    {
      title: '错误信息',
      key: 'error',
      render: (_: any, record: ImportResult) => (
        record.error ? <Text type="danger">{record.error}</Text> : '-'
      ),
    },
  ];

  return (
    <Modal
      title="导入项目"
      open={visible}
      onCancel={handleCancel}
      width={1000}
      footer={null}
      destroyOnHidden
    >
      <div className="space-y-6">
        {/* 步骤指示器 */}
        <Steps current={currentStep} size="small">
          <Step title="上传文件" icon={<UploadOutlined />} />
          <Step title="预览数据" icon={<FileTextOutlined />} />
          <Step title="执行导入" icon={<ProjectOutlined />} />
          <Step title="完成" icon={<CheckCircleOutlined />} />
        </Steps>

        {/* 步骤1: 文件上传 */}
        {currentStep === 0 && (
          <Card>
            <div className="text-center space-y-4">
              <Title level={4}>上传项目数据文件</Title>
              <Paragraph type="secondary">
                请上传包含项目信息的 Markdown 文件 (project.md)
              </Paragraph>
              
              <Alert
                message="文件格式要求"
                description={
                  <div>
                    <p>文件应包含以下列的 Markdown 表格：</p>
                    <ul>
                      <li><strong>项目名称</strong>: 项目的显示名称</li>
                      <li><strong>项目标识</strong>: 项目的唯一标识符（将作为 PingCode 项目 identifier）</li>
                      <li><strong>项目类型</strong>: scrum/kanban/waterfall/hybrid</li>
                      <li><strong>管理员</strong>: 管理员列表，用逗号分隔（将添加为项目管理员）</li>
                      <li><strong>描述</strong>: 项目描述（可选）</li>
                      <li><strong>状态</strong>: 项目状态（可选）</li>
                    </ul>
                    <p className="mt-2 text-sm">
                      <strong>示例文件：</strong> 
                      <a href="/project.md" target="_blank" className="text-blue-600 hover:text-blue-800 ml-1">
                        project.md
                      </a> 或 
                      <a href="/test-projects.md" target="_blank" className="text-blue-600 hover:text-blue-800 ml-1">
                        test-projects.md
                      </a>
                    </p>
                  </div>
                }
                type="info"
                showIcon
                className="text-left"
              />
              
              <Upload
                accept=".md,.txt"
                showUploadList={false}
                customRequest={handleFileUpload}
                maxCount={1}
              >
                <Button icon={<UploadOutlined />} size="large">
                  选择文件
                </Button>
              </Upload>
              
              <div className="mt-4 text-center">
                <Text type="secondary" className="text-sm">
                  或下载示例文件：
                  <a 
                    href="/project.md" 
                    download 
                    className="text-blue-600 hover:text-blue-800 mx-2"
                  >
                    project.md
                  </a>
                  <a 
                    href="/test-projects.md" 
                    download 
                    className="text-blue-600 hover:text-blue-800 mx-2"
                  >
                    test-projects.md
                  </a>
                </Text>
              </div>
            </div>
          </Card>
        )}

        {/* 步骤2: 数据预览 */}
        {currentStep === 1 && (
          <Card>
            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <Title level={4}>数据预览</Title>
                <Text type="secondary">共 {parsedProjects.length} 个项目</Text>
              </div>
              
              <Alert
                message="请确认以下项目信息无误后开始导入"
                description="注意：如果当前 API Token 权限不足，系统将创建模拟项目数据用于演示功能。"
                type="warning"
                showIcon
              />
              
              <Table
                dataSource={parsedProjects}
                columns={columns}
                pagination={false}
                rowKey="identifier"
                size="small"
              />
              
              <div className="flex justify-end space-x-2">
                <Button onClick={() => setCurrentStep(0)}>
                  重新上传
                </Button>
                <Button type="primary" onClick={handleImport}>
                  开始导入
                </Button>
              </div>
            </div>
          </Card>
        )}

        {/* 步骤3: 执行导入 */}
        {currentStep === 2 && (
          <Card>
            <div className="text-center space-y-4">
              <Title level={4}>正在导入项目...</Title>
              <Progress percent={importProgress} status="active" />
              <Text type="secondary">
                正在创建项目并分配管理员权限，请稍候...
              </Text>
            </div>
          </Card>
        )}

        {/* 步骤4: 导入完成 */}
        {currentStep === 3 && (
          <Card>
            <div className="space-y-4">
              <Result
                status={importResults.every(r => r.success) ? 'success' : 'warning'}
                title={
                  importResults.every(r => r.success) 
                    ? '所有项目导入成功！' 
                    : '部分项目导入失败'
                }
                subTitle={
                  <div>
                    <div>
                      {`成功: ${importResults.filter(r => r.success).length} 个，` +
                      `失败: ${importResults.filter(r => !r.success).length} 个`}
                    </div>
                    {importResults.some(r => r.success && r.project?.id?.startsWith('mock_')) && (
                      <div className="text-orange-600 text-sm mt-2">
                        ⚠️ 部分项目为模拟数据（API 权限不足时的演示功能）
                      </div>
                    )}
                  </div>
                }
              />
              
              <Divider />
              
              <Title level={5}>导入详情</Title>
              <Table
                dataSource={importResults}
                columns={resultColumns}
                pagination={false}
                rowKey={(record) => record.data.identifier}
                size="small"
              />
              
              <div className="flex justify-end">
                <Button type="primary" onClick={handleComplete}>
                  完成
                </Button>
              </div>
            </div>
          </Card>
        )}
      </div>
    </Modal>
  );
}